package com.qr.pubsub.wmyw;

import redis.clients.jedis.JedisPubSub;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import cn.krui.helper.tools.WebToolsUtils;

/**
 * @author: zc
 * email: zc8023zs@163.com
 * create_time: 2020/8/13 10:20:40
 * wmyw 模块消息处理
 */
public class SubscriberWmyw extends JedisPubSub {
    private static final Logger logger = LoggerFactory.getLogger(SubscriberWmyw.class);

    public SubscriberWmyw() {
    }

    @Override
    public void onMessage(String channel, String message) { // 收到消息会调用
        logger.info(String.format("收到redis发布的消息,频道 %s, 内容 %s", channel, message));
        if (StringUtils.isEmpty(message)){
            return;
		}
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode node = mapper.readTree(message);
            String msgType = node.path("type").asText();
            logger.info(msgType);
            Map<String, String> _header = new HashMap<>();
            _header.put("super", "mq");
            String _out_str = WebToolsUtils.httpPost(node.path("exec_url").asText(), new HashMap<>(), _header);
            logger.info(String.format("%s通知成功：%s", msgType, _out_str));
        } catch (IOException e) {
            logger.error("消息处理：system %s", e);
        }
    }

    @Override
    public void onSubscribe(String channel, int subscribedChannels) { // 订阅了频道会调用
        logger.info(String.format("成功订阅redis频道,频道 %s,订阅频道数%d", channel, subscribedChannels));
    }

    @Override
    public void onUnsubscribe(String channel, int subscribedChannels) { // 取消订阅 会调用
        logger.info(String.format("取消redis频道订阅,频道 %s,订阅频道数 %d", channel, subscribedChannels));

    }
}